package com.woniuxy.exception.handle;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.utils.ResponseResults;
import com.woniuxy.utils.ResponseState;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 无权限异常处理类
 * 处理AccessDeniedException的类，因为security在判断到当前用户没有权限时会自动跑该异常，但该异常并不会导致程序中止
 *
 * 如果在springsecurity中，想通过这种方式处理异常，需要告诉这个类，出异常了你来处理：
 *          1）去CustomSpringSecurityConfig中配置开启异常处理
 *          2）处理被拒绝请求的异常
 * */
// 给controller添加通知：如果controller抛出异常，它将去处理异常
@RestControllerAdvice
public class HandlerAccessDeniedException implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e)
            throws IOException, ServletException {
        System.out.println("处理异常AccessDeniedException");
        // 响应结果
        ResponseResults<Boolean> responseResults = new ResponseResults<>();
        responseResults.setCode(403).setMsg("你没有权限").setData(false).setState(ResponseState.NO_PERMS);
        String json = new ObjectMapper().writeValueAsString(responseResults);
        response.setHeader("Content-Type","application/json;charset=utf-8");
        response.getWriter().write(json);
    }
}
